2倍になる数のソースコード
#!/usr/bin/python
#coding: utf-8
import fcntl, os, sys, time
COUNTER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "counter.txt")
def counter():
lock_ex = False
fd_open = False
try:
fd = os.open(COUNTER, os.O_CREAT|os.O_RDWR, 0755)
fd_open = True
for i in range(100):
try:
fcntl.flock(fd, fcntl.LOCK_EX|fcntl.LOCK_NB)
lock_ex = True
except IOError:
# IOError: ロックを取得できなかった
time.sleep(0.1)
continue
else:
break
if not lock_ex:
sys.stderr.write("access_counter.cgi: File lock timeout.")
return "File lock timeout."
eof = os.lseek(fd, 0, os.SEEK_END)
os.lseek(fd, 0, os.SEEK_SET)
count = os.read(fd, eof)
try:
count = str(int(count)*2)
except ValueError:
count = "1"
os.lseek(fd, 0, os.SEEK_SET)
os.ftruncate(fd, len(count))
os.write(fd, count)
os.fsync(fd)
except AttributeError:
# AttributeError: OSの制約で利用できない関数や定数があった
return "Your environment not supported."
finally:
if lock_ex:
fcntl.flock(fd, fcntl.LOCK_UN)
if fd_open:
os.close(fd)
return count
if __name__ == "__main__":
sys.stdout.write("Content-Type: text/html\n\n%s\n" % counter())